﻿using System;
using System.Linq;
using System.Text;
using JoyfulHomeJourney.BackEnd.Api.Admin.Controllers;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

public class CheckLoginFilter : Attribute, IActionFilter
{
    private readonly string _role;
    private readonly string[] _roles;
    private readonly IConfiguration _configuration;
    private readonly ILoginServer _loginServer;

    // 构造函数接收允许的角色
    public CheckLoginFilter(string role, IConfiguration configuration, ILoginServer loginServer)
    {
        _role = role;
        _configuration = configuration;
        _loginServer = loginServer;
    }
    public CheckLoginFilter(string[] roles, IConfiguration configuration, ILoginServer loginServer)
    {
        _roles = roles;
        _configuration = configuration;
        _loginServer = loginServer;
    }
    public void OnActionExecuted(ActionExecutedContext context)
    {
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // 配置JWT参数
        var settings = new JwtSettings
        {
            SecretKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(_configuration["JWT:secret"])), // 示例随机密钥
            Issuer = _configuration["JWT:issuer"],
            Audience = _configuration["JWT:audience"],
            ExpireMinutes = 60 * 24 * 7
        };
        // 创建工具实例
        var jwtHelper = new JwtHelper(settings);
        // 解析Token
        string token = context.HttpContext.Request.Headers["Authorization"];
        if(string.IsNullOrEmpty(token) || !token.StartsWith("Bearer "))
        {
            context.Result = new UnauthorizedResult(); return;
        }
        token = token.Substring(7);
        // 检查token是否正确
        var parsedUser = jwtHelper.ParseToken<UserPayload>(token);
        if (parsedUser == null)
        {
            context.Result = new UnauthorizedResult(); return;
        }
        // 检查用户是否登录
        var account = _loginServer.CheckLogin(parsedUser.aid, parsedUser.code);
        if (account == null||account.AIsBan==1)
        {
            context.Result = new UnauthorizedResult(); return;
        }
        // 验证用户角色
        if ((_role==null&&_roles==null)||(_role!=null&&account.ARole != _role)||(_roles!=null&&!_roles.Contains(account.ARole)))
        {
            context.Result = new UnauthorizedResult(); return;
        }
        // 将用户对象存储到控制器全局对象
        if (context.Controller is BaseController controller)
        {
            controller._account = account; // 根据实际类型进行转换
        }
    }
}